package org.xenon.vote.exception;

import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.mail.MessagingException;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(value = {MessagingException.class})
    public ModelAndView MailErr(MessagingException e) {
        System.out.println(e);
        ModelAndView mv = new ModelAndView(new MappingJackson2JsonView());
        mv.addObject("status", false);
        mv.addObject("value", "mail");
        return mv;
    }

    @ExceptionHandler(value = {IOException.class})
    public ModelAndView idErr(IOException e){
        System.out.println(e);
        ModelAndView mv = new ModelAndView(new MappingJackson2JsonView());
        mv.addObject("status", false);
        mv.addObject("value", "io");
        return mv;
    }

    /**
     * 裁判要对一个已经结束但是未做清理的投票做投票等操作, 捕获该异常
     */
    @ExceptionHandler(value = {BallotStoppedException.class})
    public ModelAndView ballotStoppedErr(BallotStoppedException e){
        System.out.println(e);
        ModelAndView mv = new ModelAndView(new MappingJackson2JsonView());
        mv.addObject("status", false);
        mv.addObject("value", "stopped");
        return mv;
    }

    @ExceptionHandler(value = {BallotExistException.class})
    public ModelAndView ballotExistErr(BallotExistException e){
        System.out.println(e);
        ModelAndView mv = new ModelAndView(new MappingJackson2JsonView());
        mv.addObject("status", false);
        mv.addObject("value", "exist");
        return mv;
    }

    @ExceptionHandler(value = {DataIntegrityViolationException.class})
    public ModelAndView dataIntegrityViolation(DataIntegrityViolationException e){
        System.out.println(e);
        ModelAndView mv = new ModelAndView(new MappingJackson2JsonView());
        mv.addObject("status", false);
        mv.addObject("value", "data");
        return mv;
    }


    @ExceptionHandler(value = {Exception.class})
    public ModelAndView unknownErr(Exception e){
        e.printStackTrace();
        ModelAndView mv = new ModelAndView(new MappingJackson2JsonView());
        mv.addObject("status", false);
        mv.addObject("value", e.getClass().toString());
        return mv;
    }
}
